//
//  BVC.swift
//  WKWeb
//
//  Created by 郑东喜 on 2016/12/6.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit
import WebKit

class BVC: UIViewController,WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate {
    
    var webView: WKWebView!
    
    
    var url : String = ""
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        print("viewWillAppear2")
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        
        configuration.userContentController = userContentController
        
        // 设置偏好设置
        let preferences = WKPreferences()
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        
        configuration.processPool = WKProcessPool()
        webView = WKWebView.init(frame: view.bounds, configuration: configuration)
        
        webView.uiDelegate = self
        webView.navigationDelegate = self

        let urlStr = urlArray.lastObject
        
        webView.load(URLRequest.init(url: URL.init(string: urlStr as! String)!))
        view.addSubview(webView)
        
        //添加刷新控件
        let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(refreshWebView(sender:)), for: UIControlEvents.valueChanged)
        webView.scrollView.addSubview(refreshControl)
    }

    //刷新函数
    func refreshWebView(sender: UIRefreshControl) {

        self.loadViewIfNeeded()

        sender.endRefreshing()
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
    
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let hostname = navigationAction.request.url?.host?.lowercased()
        
        print(urlArray.count)
        url = (navigationAction.request.url?.absoluteString)!
        
        if navigationAction.navigationType == WKNavigationType.linkActivated {
            
            //如果为本身或者本身携带#的url进行自身刷新。
            if url == "http://yungou.ie1e.com/app/cart.aspx" || url == "http://yungou.ie1e.com/app/cart.aspx#" {
                
                //自刷新
                self.webView.load(URLRequest.init(url: URL.init(string: url)!))
                
                urlArray.removeAllObjects()
                
            } else {
                print(urlArray)
                urlArray.add(url)
                aaa(str: urlArray.lastObject as! String)
            }
            
            decisionHandler(.cancel)
            //            ///判断
            //            1首页，返回，数组清空
            
            
            //            3.当前页不动
            //            不满足。创建新页面（添加数组，最后一个元素）
            
            //            4.判断
            //            5.新页面才记录。
            
            //判断是否有?，请求参数结尾
//            if url.contains("?") {
//                url = url + ("")
//            } else {
//                url = url + ("?&")
//            }
//            
        } else {
            decisionHandler(.allow)
            
        }
        
        
    }
    
    //url---
    func aaa(str : String) -> Void {
        
        
        let vvv = ViewController()
        vvv.url = str
        self.navigationController?.pushViewController(vvv, animated: true)
    }
    
//    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
//        self.navigationItem.title = self.webview.title
//    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.navigationItem.title = self.webView.title
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        decisionHandler(.allow)
    }
    
}
